package com.hao.wms.service.impl;

import com.hao.wms.VO.SystemMenuVO;
import com.hao.wms.dao.ISystemMenuDao;
import com.hao.wms.domain.SystemMenu;
import com.hao.wms.query.PageResult;
import com.hao.wms.query.QueryObject;
import com.hao.wms.query.SystemMenuQueryObject;
import com.hao.wms.service.ISystemMenuService;
import com.hao.wms.util.UserContext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SystemMenuServiceImpl implements ISystemMenuService {
    private ISystemMenuDao dao;


    public void setDao(ISystemMenuDao dao) {
        this.dao = dao;
    }

    @Override
    public void save(SystemMenu systemMenu) {
        dao.save(systemMenu);

    }

    @Override
    public void update(SystemMenu systemMenu) {
        dao.update(systemMenu);

    }

    @Override
    public void delete(SystemMenu systemMenu) {
        SystemMenuQueryObject qo = new SystemMenuQueryObject();
        qo.setParentId(systemMenu.getId());
        PageResult result = dao.query(qo);
        if (result.getTotalCount() > 0) {
            throw new RuntimeException("不能删除包含子菜单的目录！");
        }
        dao.delete(systemMenu);

    }

    @Override
    public SystemMenu get(Long id) {
        return dao.get(id);
    }

    @Override
    public List<SystemMenu> list() {
        return dao.list();
    }

    @Override
    public PageResult query(QueryObject qo) {
        return dao.query(qo);
    }

    @Override
    public List<SystemMenuVO> queryMenuByParentId(Long parentId) {
        List<SystemMenuVO> menus = new ArrayList<>();
        SystemMenu current = dao.get(parentId);
        addMenus(menus, current);
        Collections.reverse(menus);
        return menus;
    }

    private void addMenus(List<SystemMenuVO> menus, SystemMenu current) {
        if (current != null) {
            SystemMenuVO parent = new SystemMenuVO();
            parent.setId(current.getId());
            parent.setName(current.getName());
            menus.add(parent);
            addMenus(menus, current.getParent());
        }
    }

    @Override
    public List<SystemMenu> queryChildrenMenus() {
        return dao.queryChildrenMenus();
    }

    @Override
    public List<SystemMenu> queryMenuByParentSn(String parentSn) {
        if (UserContext.getUser().isAdmin()) {
            return dao.queryMenusBySn(parentSn);
        }else {
            return dao.queryMenusBySnAndRole(parentSn,UserContext.getUser().getRoles());
        }
    }
}
